package com.mj.listen3.链表;

/**
 * https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
 */
public class _剑指Offer18_删除链表的节点 {

    /**
     * 非虚拟头节点法，需要考虑删除的节点是否是头和尾
     */
    public ListNode deleteNode(ListNode head, int val) {
        if (head == null) return head;

        if (head.val == val) {
            // 删除的是头节点
            head = head.next;
        }

        ListNode pre = head;
        ListNode cur = head.next;

        while (cur != null) {
            if (cur.val == val) {
                break;
            }
            pre = cur;
            cur = cur.next;
        }

        // cur不为空，说明找到了要删除的节点，那么就删除cur位置的节点
        if (cur != null) {
            pre.next = cur.next;
        }

        // cur为空，说明未找到要删除的节点。不用处理

        return head;
    }

    /**
     * 虚拟头节点法
     */
    public ListNode deleteNode2(ListNode head, int val) {
        if (head == null) return head;

        ListNode virtualHead = new ListNode(0);
        virtualHead.next = head;
        ListNode pre = virtualHead;

        ListNode cur = head;
        while (cur != null) {
            if (cur.val == val) {
                break;
            }
            pre = cur;
            cur = cur.next;
        }

        if (cur != null) {
            pre.next = cur.next;
        }

        // cur为null说明没有可以删除的节点

        return virtualHead.next;
    }
}
